<template>
	<div class="wrapper">
		<div>
			<!-- 当前商品id:{{id}} -->
			<div>
				<el-select v-model="goodsId" placeholder="请选择" style="width: 180px;" @change="getList">
					<el-option :label="item.goodsName" :value="item.goodsId" v-for="(item,index) in postList"
						:key="index" />
				</el-select>
				<el-date-picker style="margin-left: 8px;width:180px;" @change="handleDate" :clearable="false"
					:picker-options="pickerOptions1" v-model="val2" type="month" placeholder="选择月" />
			</div>
			<div v-loading="vLoading">
				<el-calendar :value="elCalendarValue">
					<template slot="dateCell" slot-scope="{date, data}">
						<div class="date-wrapper" :class="(showDateFn(date,data)&&showLastTime(date))?('_'+getclosingType(data)):''"
							@click.stop="handleClick(date, data)">
							<span class="day">{{data.day.split('-').slice(1)[1]}}</span>
							<div class="price" v-if="showDateFn(date,data)">￥{{getDateData(data.day,'price')}}</div>
							<div class="numb" v-if="showDateFn(date,data)"
								:class="getDateData(data.day,'roomNumb')>minInventory?'numb-color':''">
								可入住{{getDateData(data.day,'roomNumb')}}</div>
							<div class="on-show-type" v-if="showDateFn(date,data) && showLastTime(date)" @click.stop="handleType(data)"
								:class="'_'+getclosingType (data)">
								{{getclosingType (data) == 0?'已开房':'已关房'}}
							</div>
						</div>
					</template>
				</el-calendar>
			</div>
		</div>
		<el-dialog :title="title" :visible.sync="open" width="500px" append-to-body :close-on-click-modal="false">
			<div style="padding-right: 40px;">
				<el-form ref="form" :model="form" :rules="rules" label-width="100px" v-loading="diLogLoading">
					<el-row>
						<el-col :span="24">
							<el-form-item label="价格:" prop="dayPrice">
								<el-input v-model="form.dayPrice" placeholder="请输入价格" style="width:240px;"></el-input>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row>
						<el-col :span="24">
							<el-form-item label="重复:" prop="type">
								<el-select v-model="form.type" placeholder="请选择" clearable style="width:240px;"
									@change="handleChange(1)">
									<el-option :value="item.value" :label="item.label"
										v-for="(item,index) in ticketDicData" :key="index" />
								</el-select>
								<div class="week" v-if="form.type == '3'">
									<div class="week-item" :style="weelItemStyle(item)" v-for="(item,index) in weekData"
										@click="handleWeekSelector(item)" :key="index">{{item.label}}
									</div>
								</div>
							</el-form-item>
						</el-col>
					</el-row>

					<el-row v-if="form.type == '2'">
						<el-col :span="24">
							<el-form-item label="结束重复:" prop="f3">
								<el-select v-model="form.f3" placeholder="请选择结束重复" clearable style="width:240px;"
									@change="handleChange(2)">
									<el-option :value="item" :label="item" v-for="(item,index) in endTimeData"
										:key="index" />
								</el-select>
								<br />
								<el-date-picker v-if="form.f3 == '于日期'" v-model="form.endDate" type="date"
									value-format="yyyy-MM-dd" placeholder="选择日期" style="width:240px;margin-top:8px;"
									:picker-options="pickerOptions2" />
							</el-form-item>
						</el-col>
					</el-row>

				</el-form>
			</div>
			<div slot="footer" class="dialog-footer" v-if="!diLogLoading">
				<el-button type="primary" @click="submitForm" :loading="btnLoading">保 存</el-button>
				<el-button @click="cancel" :disabled="btnLoading">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 设置当天时间 -->
		<closing-type ref="closing-type" @on-success="getList" />
	</div>
</template>
<script>
	import {
		priceCalendarList,
		goodsList,
		priceCalendarUpdate
	} from "@/api/shopping/content";
	import ClosingType from './components/ClosingType/index.vue';
	export default {
		name: "ShoppingDate",
		components: {
			ClosingType
		},
		data() {
			return {
				value: new Date(),
				val2: new Date(),
				goodsId: '',
				options: null,
				postList: [],
				lastOnshowTime: '',
				fromOnshowTime:'',
				ticketDicData: [{
						label: '当天',
						value: '1'
					},
					{
						label: '每天',
						value: '2'
					},
					{
						label: '每周',
						value: '3'
					}
				],
				endTimeData: [
					'于日期',
					'永不'
				],
				weekData: [{
						label: '周一',
						value: '周一'
					},
					{
						label: '周二',
						value: '周二'
					},
					{
						label: '周三',
						value: '周三'
					},
					{
						label: '周四',
						value: '周四'
					},
					{
						label: '周五',
						value: '周五'
					},
					{
						label: '周六',
						value: '周六'
					},
					{
						label: '周日',
						value: '周日'
					}
				],
				elCalendarValue: "",
				btnLoading: false,
				diLogLoading: false,
				vLoading: false,
				open: false,
				title: "",
				form: {},
				rules: {
					dayPrice: {
						required: true,
						message: '请输入价格',
						trigger: 'blur'
					},
					type: {
						required: true,
						message: '请选择',
						trigger: 'blur'
					}
				},
				dateData: [],
				selectorArr: [],
				minInventory: 0,
				pickerOptions2: {
					disabledDate: date => {
						let maxTime = new Date();
						let dateNow = new Date();
						dateNow.setDate(dateNow.getDate() - 1);
						dateNow = this.dateFormat("YYYY/mm/dd", dateNow);
						dateNow = new Date(dateNow);
						maxTime.setMonth(maxTime.getMonth() + 12);
						maxTime.setDate(0);
						if (date.getTime() > dateNow.getTime() && date.getTime() < maxTime.getTime()) return false;
						return true;
					}
				},
				pickerOptions1: {
					disabledDate: (date) => {
						let nowDate = new Date();
						let oldDate = '';
						let minTime = '';
						let maxTime = '';
						nowDate = new Date(
							`${nowDate.getFullYear()}/${(nowDate.getMonth()+1)<10?'0'+(nowDate.getMonth()+1):nowDate.getMonth()+1}`
						);
						oldDate = new Date(
							`${date.getFullYear()}/${(date.getMonth()+1)<10?'0'+(date.getMonth()+1):date.getMonth()+1}`
						);
						minTime = nowDate.getTime();
						nowDate.setMonth(nowDate.getMonth() + 12);
						maxTime = nowDate.getTime();
						if (minTime <= oldDate.getTime() && maxTime > oldDate.getTime()) return false;
						return true;
					}
				}
			}
		},
		methods: {
			handleType(data) {
				let options = this.getDateData(data.day);
				this.$nextTick(() => {
					this.$refs['closing-type'].init(options)
				})
			},
			getclosingType (data) {
				let options = this.getDateData(data.day)
				let closingType  = 0;
				if (options) {
					closingType  = options.closingType ;
				};
				return closingType ;
			},
			handleChange(state) {
				if (state == 1) {
					this.form.f3 = '';
					this.selectorArr = [];
				};
				this.form.f4 = '';
			},
			showLastTime(date){
				let nowTime = new Date(this.dateFormat('YYYY/mm/dd', date)).getTime();
				let stratTime = new Date(this.dateFormat('YYYY/mm/dd', new Date(this.fromOnshowTime))).getTime();
				let endTime = new Date(this.dateFormat('YYYY/mm/dd', new Date(this.lastOnshowTime))).getTime();
				if(this.lastOnshowTime == 0){ //永不下架
					return nowTime>=stratTime
				};
				return nowTime>=stratTime && nowTime<=endTime;
			},
			showDateFn(date, data) {
				let startTime = new Date(this.dateFormat('YYYY/mm/dd', date)).getTime();
				let endTime = new Date(this.dateFormat('YYYY/mm/dd', new Date())).getTime();
				return startTime >= endTime;
			},
			handleClick(date, data) {
				this.form = {
					dayPrice: '',
					type: '',
					f3: '',
					endDate: '',
					f5: '',
					f6: '',
				};
				this.options = null;
				if (!this.getDateData(data.day, "data")) return;
				let startTime = new Date(this.dateFormat('YYYY/mm/dd', new Date(this.getDateData(data.day, "data")
					.dayTime))).getTime();
				let endTime = new Date(this.dateFormat('YYYY/mm/dd', new Date())).getTime();
				if (startTime < endTime) return;
				if (this.getDateData(data.day, "data")) {
					this.options = this.getDateData(data.day, "data");
					this.open = true;
				}
			},
			cancel() {
				this.open = false;
				this.btnLoading = false;
				return;
			},
			handleWeekSelector(options) {
				let arr = []
				if (this.selectorArr.some(item => item == options.value)) {
					this.selectorArr.forEach(item => {
						if (item != options.value) arr.push(item);
					});
					this.selectorArr = arr;
				} else {
					this.selectorArr.push(options.value);
				}
			},
			weelItemStyle(options) {
				if (this.selectorArr.some(item => item == options.value)) return 'background-color:#cccccc;color:#ffffff;'
			},
			handleDate(e) {
				this.elCalendarValue = this.dateFormat("YYYY-mm", e);
				this.getList();
			},
			getDateData(day, who) {
				if (!this.dateData.length) return;
				let price = 0; //价格
				let roomNumb = 0; //房间数量
				let data = null; //参数
				this.dateData.forEach(item => {
					if (day == this.dateFormat("YYYY-mm-dd", new Date(item.dayTime))) {
						price = item.dayPrice;
						roomNumb = item.availableRooms;
						data = item;
					}
				});
				if (who == "price") return price;
				if (who == "roomNumb") return Number(roomNumb);
				return data;
			},
			async getList() {
				try {
					this.vLoading = true;
					let res = await priceCalendarList({
						dayTime: this.elCalendarValue,
						goodsId: this.goodsId
					});
					this.dateData = res.rows; //日历内容
					this.vLoading = false;
					return;
				} catch (e) {
					this.vLoading = false;
				}
			},
			getCountDays(curDate = new Date()) { //获取当月天数
				curDate.setMonth(curDate.getMonth() + 1);
				curDate.setDate(0);
				return curDate.getDate();
			},
			dateFormat(fmt, date) {
				let ret;
				const opt = {
					"Y+": date.getFullYear().toString(), // 年
					"m+": (date.getMonth() + 1).toString(), // 月
					"d+": date.getDate().toString(), // 日
					"H+": date.getHours().toString(), // 时
					"M+": date.getMinutes().toString(), // 分
					"S+": date.getSeconds().toString() // 秒
				};
				for (let k in opt) {
					ret = new RegExp("(" + k + ")").exec(fmt);
					if (ret) {
						fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
					}
				}
				return fmt;
			},
			submitForm() {
				this.$refs['form'].validate(async valid => {
					try {
						if (valid) {
							let data = {
								id: this.options.id,
								type: this.form.type,
								dayPrice: this.form.dayPrice,
								endDate: this.form.endDate,
								goodsName: this.options.goodsName,
								weeks: this.selectorArr.join(",")
							};
							for (let i in data) {
								if (!data[i]) delete data[i];
							};
							this.btnLoading = true;
							let res = await priceCalendarUpdate(data);
							await this.cancel();
							await this.getList();
						}
					} catch (e) {
						this.btnLoading = false;
					}
				})
			}
		},
		async created() {
			this.goodsId = this.$route.params.id;
			this.minInventory = this.$route.query.minInventory;
			this.lastOnshowTime = Number(this.$route.query.lt);
			this.fromOnshowTime = Number(this.$route.query.st);
			this.elCalendarValue = this.dateFormat("YYYY-mm", new Date());
			let res = await goodsList({
				pageNum: 1,
				pageSize: 999
			});
			this.postList = res.rows;
			this.getList();
		}
	}
</script>
<style lang="scss" scoped>
	::v-deep .el-calendar {
		.el-calendar__body table {
			border-spacing: 6px 0px;

			td {
				border-left: 1px solid #EBEEF5;
				.el-calendar-day{
					height: 108px;
				}
			}
		}

		.el-calendar__header {
			display: none;
		}

		.el-calendar-day {
			padding: 0 !important;
		}

		.el-calendar-table__row {
			.is-selected {
				background-color: transparent !important;
			}
			.next {
				display: none;
			}

			.prev {
				// pointer-events: none;
				.price,
				.numb,
				.on-show-type{
					display: none;
				}
			}
		}
	}

	.week {
		display: flex;
		margin-top: 8px;

		.week-item {
			font-size: 12px;
			border: 1px solid #cccccc;
			height: 25px;
			line-height: 25px;
			width: 45px;
			text-align: center;
			cursor: pointer;
			user-select: none;

			&+.week-item {
				margin-left: 4px;
			}
		}
	}

	.wrapper {
		padding: 20px;
		$height: 24px;
		$bottom: 8px;
		.date-wrapper {
			position: relative;
			width: 100%;
			height: 100%;
			font-size: 14px;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			justify-content: flex-end;
			
			.on-show-type {
				position: absolute;
				right: 6px;
				bottom: $bottom;
				width: 60px;
				border-radius: 5px;
				height: $height;
				line-height: $height;
				text-align: center;
				font-size: 12px;
				color: #ffffff;
				background-color: rgba(75, 121, 2, 1);
			}

			.on-show-type._0 {
				background-color: rgba(75, 121, 2, 1);
			}

			.on-show-type._1 {
				background-color: rgba(255, 89, 64, 1);
			}

			.day {
				position: absolute;
				right: 8px;
				top: 8px;
				color: black;
			}

			.numb,
			.price {
				padding-left: 18px;
				border: 1px solid #cccccc;
				width: 100px;
				border-radius: 2px;
				position: relative;
				margin-left: 6px;
				height: $height;
				line-height: $height;
				font-size: 14px;
				color: black;

				&::after {
					content: "";
					position: absolute;
					left: 6px;
					height: 6px;
					width: 6px;
					top: 50%;
					margin-top: -3px;
					border-radius: 50%;
					background-color: #333333;
				}
			}

			.numb {
				margin-top: 4px;
				color: red;
				margin-bottom: $bottom;
			}

			.numb-color {
				color: black;
			}

			.numb::after {
				background-color: red;
			}

			.numb-color::after {
				background-color: black;
			}
		}

		.date-wrapper._1 {
			background-color: rgb(255, 233, 226);
		}
	}
</style>
